
import * as Koa from 'koa';
import config from './config';
import * as crypto from 'crypto';
import { Exceptions } from '../kalend';
import { platform_userService } from '../service/platform_user';
import { menuService } from '../service/menu';

/**token验证 */
export async function verification(ctx: Koa.Context, next: Function) {
    var url = ctx.path;
    //api/log 不做token验证
    console.log('url=' + url);
    if (url.indexOf("/usergame") < 0 && url.indexOf("/game/querygame") < 0 && url.indexOf("/test/log") < 0 
    && url.indexOf("/file") < 0 && url.indexOf("/wechat/order_notice") < 0 && url.indexOf("/api/web_version") < 0 
    && url.indexOf("/city/save") < 0 && url.indexOf("/city/query") < 0 && url.indexOf("/api/test22") < 0) {
        let jwtConfig = config.get('tokensoft');
        var str = ctx.originalUrl.substring(1) + jwtConfig.key;
        console.log('前台url和key' + str);
        var token = crypto.createHash('md5').update(str).digest('hex');
        console.log('头文件中token' + ctx.headers.tokensoft);
        console.log('签名后token' + token);
        if (token !== ctx.headers.tokensoft) {
            throw Exceptions.tokenValidFail();
        }
        let ts = +ctx.query.timestamp;
        let curenttime = Math.floor(Date.now() / 1000);
        let mi = (curenttime - ts) / 60
        /** token有效时间2分钟 */
        const timeout = config.get("timeoutToken");
        if (mi > timeout) {
            console.log('--------------------接口校验失败：接口过期----------------------');
            throw Exceptions.known("接口校验失败，请检查本地时间是否同步网络时间");
        }
    }
    await next();
}

/**url验证 */
export async function verificationUrl(ctx: Koa.Context, next: Function) {
    var url = ctx.headers.route;
    var epid = ctx.headers.epid;
    // 不做url验证
    console.log('url=' + url);
    if (url) {
        url = url.substring(1);
        console.log('url=' + url);
        const user = await platform_userService.queryMenuById(epid);
        const menus = await menuService.queryalls();
        const ismenus = menus.findIndex((a) => {
            return a.url === url;
        });
        const isauth = user.findIndex((a) => {
            return a.url === url;
        });
        if (ismenus > -1 && isauth < 0) {
            throw Exceptions.known("无权限访问当前页面");
        }
    }

    await next();
}